package com.gc.web.controller.business;

import cn.hutool.core.date.DateUtil;
import com.gc.business.domain.Attachment;
import com.gc.business.service.IAttachmentService;
import com.gc.common.annotation.Log;
import com.gc.common.base.AjaxResult;
import com.gc.common.base.Result;
import com.gc.common.config.Global;
import com.gc.common.enums.BusinessType;
import com.gc.common.support.Convert;
import com.gc.common.utils.DateUtils;
import com.gc.common.utils.file.FileUtils;
import com.gc.common.utils.file.MimeTypeUtils;
import com.gc.common.utils.poi.ExcelUtil;
import com.gc.framework.config.ServerConfig;
import com.gc.framework.util.FileUploadUtils;
import com.gc.framework.util.ShiroUtils;
import com.gc.framework.web.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

/**
 * 附件 控制层
 * 
 * @author liujinteng
 * @date 2020-11-06
 */
@Slf4j
@Controller
@RequestMapping("/business/attachment")
public class AttachmentController extends BaseController {
    private String prefix = "business/attachment";
	
	private final IAttachmentService attachmentService;

	private final ServerConfig serverConfig;

	/**
	 * 文件上传路径
	 */
	public static final String UPLOAD_PATH = "/profile/upload/";

	@Autowired
	public AttachmentController(IAttachmentService attachmentService,ServerConfig serverConfig) {
		this.attachmentService = attachmentService;
		this.serverConfig = serverConfig;
	}

	/**
	*  列表页
	*/
	@RequiresPermissions("business:attachment:view")
	@GetMapping
	public String attachment(){
	    return prefix + "/attachment";
	}

	/**
	 * 新增页
	 */
	@GetMapping("/add")
	public String add(){
		return prefix + "/add";
	}

	/**
	 * 编辑页
	 */
	@GetMapping("/edit/{attachId}")
	public String edit(@PathVariable("attachId") Long attachId, ModelMap mmap){
		Attachment attachment = attachmentService.getById(attachId);
		mmap.put("attachment", attachment);
		return prefix + "/edit";
	}
	
	/**
	 * 查询附件列表
	 */
	@RequiresPermissions("business:attachment:list")
	@PostMapping("/list")
	@ResponseBody
	public Result list(Attachment attachment){
		startPage();
        List<Attachment> list = attachmentService.list(attachment);
		return Result.success(getDataTable(list));
	}

	/**
	 * 新增保存附件
	 */
	@RequiresPermissions("business:attachment:add")
	@Log(title = "附件", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public Result addSave(Attachment attachment){
		attachment.setCreateTime(DateUtil.date());
		attachment.setCreateBy(ShiroUtils.getLoginName());
		attachmentService.save(attachment);
		return Result.success();
	}

	/**
	 * 修改保存附件
	 */
	@RequiresPermissions("business:attachment:edit")
	@Log(title = "附件", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public Result editSave(Attachment attachment){
		attachment.setUpdateTime(DateUtil.date());
		attachment.setUpdateBy(ShiroUtils.getLoginName());
		attachmentService.updateById(attachment);
		return Result.success();
	}
	
	/**
	 * 删除附件
	 */
	@Log(title = "附件", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public Result remove(String ids){
		Long[] longIds = Convert.toLongArray(ids);
		attachmentService.removeByIds(Arrays.asList(longIds));
		return Result.success(ids);
	}

	/**
	 * 导出附件列表
	 */
	@RequiresPermissions("business:attachment:export")
	@PostMapping("/export")
	@ResponseBody
	public Result export(Attachment attachment){
		List<Attachment> list = attachmentService.list(attachment);
		ExcelUtil<Attachment> util = new ExcelUtil<>(Attachment.class);
		util.exportExcel(list, "attachment");
		return Result.success();
	}

	/**
	 * 通用单个附件上传接口
	 */
	@PostMapping("/upload")
	@ResponseBody
	public AjaxResult upload(MultipartFile file){
		try {
			// 上传文件路径
			String filePath = Global.getUploadPath();
			// 上传并返回新文件名称
			String fileName = FileUploadUtils.upload(filePath, file);
			String url = serverConfig.getUrl() + UPLOAD_PATH + fileName;
			// 获取原文件名称
			String originalFileName = file.getOriginalFilename();
			// 获取文件名称后缀
			String extension = FileUploadUtils.getExtension(file);
			// 校验是否为文档类型
			boolean flag = FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.IMAGE_EXTENSION);
			AjaxResult ajax = AjaxResult.success();
			ajax.put("originalFileName",originalFileName);
			ajax.put("fileName", fileName);
			ajax.put("url", url);
			ajax.put("location", url);
			ajax.put("relative_url", UPLOAD_PATH + fileName);
			Attachment attachment = new Attachment();
			attachment.setIsImg(flag ? 0 : 1);
			attachment.setIconUrl(FileUploadUtils.checkAttachSaveIcon(extension));
			attachment.setAttachUrl(url);
			String attachSize = FileUtils.convertFileSize(file.getSize());
			attachment.setAttachSize(attachSize);
			attachment.setAttachTitle(originalFileName);
			attachment.setCreateTime(DateUtil.date());
			attachment.setCreateBy(ShiroUtils.getLoginName());
			attachmentService.save(attachment);
			return ajax;
		} catch (Exception e) {
			return AjaxResult.error(e.getMessage());
		}
	}

	/**
	 * 通用多个附件上传接口
	 */
	@PostMapping("/uploadMore")
	@ResponseBody
	public AjaxResult uploadMore(@RequestParam("file") MultipartFile[] files){
		try {
			// 上传文件路径
			String filePath = Global.getUploadPath();
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < files.length; i++) {
				Attachment attachment = new Attachment();
				// 上传并返回新文件名称
				String fileName = FileUploadUtils.upload(filePath, files[i]);
				String url = serverConfig.getUrl() + UPLOAD_PATH + fileName;
				// 获取原文件名称
				String originalFileName = files[i].getOriginalFilename();
				// 获取文件名称后缀
				String extension = FileUploadUtils.getExtension(files[i]);
				// 校验是否为文档类型
				boolean flag = FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.IMAGE_EXTENSION);
				attachment.setIsImg(flag ? 0 : 1);
				attachment.setIconUrl(FileUploadUtils.checkAttachSaveIcon(extension));
				attachment.setAttachUrl(url);
				attachment.setAttachTitle(originalFileName);
				String attachSize = FileUtils.convertFileSize(files[i].getSize());
				attachment.setAttachSize(attachSize);
				attachment.setCreateTime(DateUtil.date());
				attachment.setCreateBy(ShiroUtils.getLoginName());
				attachmentService.save(attachment);
				if (i == files.length-1){
					sb.append(attachment.getAttachId());
				}else {
					sb.append(attachment.getAttachId()+",");
				}
			}
			AjaxResult ajax = AjaxResult.success();
			ajax.put("url", sb.toString());
			return ajax;
		} catch (Exception e) {
			return AjaxResult.error(e.getMessage());
		}
	}
}
